import React, { useState, useEffect, useMemo } from 'react';
import { Button, Modal, Form, Select, Input, InputNumber, message } from 'antd';
import planIcon from '@/assets/img/plan_icon.png';
import styles from './index.less';
import { HttpCode } from '#/utils/contacts.js';
const ApplyModalComponent = ({
  showApply,
  onClose,
  onOk,
  config = {},
  type,
  data = [],
  applyType,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({});
  useEffect(() => {
    if (applyType == 'edit' && showApply) {
      setFormData(data);
      form.setFieldsValue({ ...data });
    } else {
      setFormData({});
      form.resetFields();
    }
  }, [data, showApply]);

  // 取消
  const _onCancel = () => {
    onClose();
  };
  const setOptions = useMemo(() => {
    let options = {
      machineOptions: [],
      dimStationOptions: [],
    };
    if (type == 'place') {
      let { machineInfo, dimStationInfo, dimStationOptions } = config;
      if (machineInfo.length > 0 && dimStationInfo.length > 0) {
        options.machineOptions = machineInfo.map((item) => {
          return { label: item.unitType, value: item.unitType };
        });
        options.dimStationOptions = dimStationOptions;
      }
    }
    return options;
  }, [config, type]);
  // 确认
  const _onOk = async () => {
    form &&
      form.validateFields().then(async (value) => {
        setLoading(true);
        let res = await onOk?.(value);
        if (res?.statusCode === HttpCode.SUCCESS) {
          message.success('提交成功！');
          onClose(true);
        } else {
          message.error(res?.message);
        }
        setLoading(false);
      });
  };

  const selectChange = (value, type) => {
    if (type == 'dimStation') {
      let obj = { ...formData, stationId: value };
      config.dimStationInfo.map((item) => {
        if (item.stationId == value) {
          obj.stationCapacity = item.stationCapacity;
        }
      });
      if (!obj?.stationCapacity) {
        obj.stationCapacity = '';
      }
      setFormData(obj);
    } else {
      config.machineInfo.map((item) => {
        if (item.unitType == value) {
          setFormData({
            ...formData,
            cutoutWindspeed: item.cutoutWindspeed,
            ratedPower: item.ratedPower,
          });
        }
      });
    }
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={loading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
        确定
      </Button>,
    ];
  };
  const formItems_1 = () => {
    return [
      <Form.Item label="场站编码" name="stationId">
        <div>{formData?.stationId}</div>
      </Form.Item>,
      <Form.Item label="场站名称" name="stationName">
        <Select
          showSearch={true}
          filterOption={(val, option) => {
            return option?.children?.includes(val);
          }}
          onChange={(value) => {
            selectChange(value, 'dimStation');
          }}
        >
          {setOptions.dimStationOptions?.map((d) => {
            return (
              <Select.Option key={d?.value ?? ''} value={d?.value ?? ''}>
                {d?.label ?? ''}
              </Select.Option>
            );
          })}
        </Select>
      </Form.Item>,
      <Form.Item
        label="机组类型"
        name="unitType"
        rules={[
          {
            required: true,
            message: `请选择机组类型`,
          },
        ]}
      >
        <Select
          showSearch={true}
          filterOption={(val, option) => {
            return option?.children?.includes(val);
          }}
          onChange={(value) => {
            selectChange(value, 'machine');
          }}
        >
          {setOptions.machineOptions?.map((d) => {
            return (
              <Select.Option key={d?.value ?? ''} value={d?.value ?? ''}>
                {d?.label ?? ''}
              </Select.Option>
            );
          })}
        </Select>
      </Form.Item>,
      <Form.Item label="容量（万kWh）" name="stationCapacity">
        <div>{!!formData?.stationCapacity ? (formData?.stationCapacity / 10).toFixed(2) : ''}</div>
      </Form.Item>,
      <Form.Item
        label="风机台数"
        name="fanCount"
        rules={[
          {
            required: true,
            message: `请填写风机台数`,
          },
          { pattern: /^\d{0,10}$/, message: '必须为整数且长度不可超过4位' },
        ]}
      >
        <InputNumber style={{ width: 200 }} max={9999} />
      </Form.Item>,
      <Form.Item label="额定功率（kW）" name="ratedPower">
        <div>{formData?.ratedPower}</div>
      </Form.Item>,
      <Form.Item label="切出风速10分钟m/s" name="cutoutWindspeed">
        <div>{formData?.cutoutWindspeed}</div>
      </Form.Item>,
    ];
  };
  const formItems_2 = () => {
    return [
      <Form.Item
        label="机组类型"
        name="unitType"
        rules={[
          {
            required: true,
            message: `请填写机组类型`,
          },
        ]}
      >
        <Input maxLength={30} />
      </Form.Item>,
      <Form.Item
        label="额定功率（kW）"
        name="ratedPower"
        rules={[
          {
            required: true,
            message: `请填写额定功率`,
          },
          { pattern: /^\d{0,10}$/, message: '必须为整数且长度不可超过8位' },
        ]}
      >
        <InputNumber style={{ width: 200 }} max={99999999} />
      </Form.Item>,
      <Form.Item
        label="切出风速10分钟m/s"
        name="cutoutWindspeed"
        rules={[
          {
            required: true,
            message: `请填写切出风速且长度不可超过3位`,
          },
        ]}
      >
        <InputNumber style={{ width: 200 }} max={999} />
      </Form.Item>,
    ];
  };
  return (
    <Modal
      className={styles.modal}
      centered
      width={500}
      maskClosable={false}
      visible={showApply}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>{applyType == 'add' ? '新增' : '编辑'}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="apply"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          // initialValues={data}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          {type == 'place' ? formItems_1 : formItems_2}
        </Form>
      </div>
    </Modal>
  );
};

export default ApplyModalComponent;
